<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>代码生成器 - CRUD Generator</title>
    
    <!-- 字体 -->
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <!-- Bootstrap CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css" rel="stylesheet">
    
    <!-- 代码高亮 -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/themes/prism-tomorrow.min.css" rel="stylesheet">
    
    <!-- 通用样式 -->
    <link href="/css/common.css" rel="stylesheet">
    
    <style>
        body {
            font-family: 'Inter', sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
        }

        .main-container {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            margin: 2rem 0;
            overflow: hidden;
        }

        .page-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 3rem 0;
            text-align: center;
            position: relative;
            overflow: hidden;
        }

        .page-header::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grain" width="100" height="100" patternUnits="userSpaceOnUse"><circle cx="25" cy="25" r="1" fill="white" opacity="0.1"/><circle cx="75" cy="75" r="1" fill="white" opacity="0.1"/><circle cx="50" cy="10" r="0.5" fill="white" opacity="0.1"/><circle cx="20" cy="80" r="0.5" fill="white" opacity="0.1"/><circle cx="90" cy="30" r="0.5" fill="white" opacity="0.1"/></pattern></defs><rect width="100" height="100" fill="url(%23grain)"/></svg>');
            opacity: 0.3;
        }

        .page-header h1 {
            font-size: 3rem;
            font-weight: 700;
            margin-bottom: 1rem;
            position: relative;
            z-index: 1;
        }

        .page-header p {
            font-size: 1.2rem;
            opacity: 0.9;
            position: relative;
            z-index: 1;
        }

        .sql-input-section {
            padding: 3rem 0;
        }

        .sql-editor {
            border: 2px solid #e9ecef;
            border-radius: 15px;
            background: #f8f9fa;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }

        .sql-editor:focus-within {
            border-color: #667eea;
            box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
            transform: translateY(-2px);
        }

        .sql-editor textarea {
            border: none;
            background: transparent;
            font-family: 'Fira Code', 'Monaco', 'Consolas', monospace;
            font-size: 14px;
            line-height: 1.6;
            resize: vertical;
            min-height: 300px;
        }

        .sql-editor textarea:focus {
            box-shadow: none;
            outline: none;
        }

        .editor-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 1rem 1.5rem;
            font-weight: 600;
            display: flex;
            align-items: center;
            justify-content: between;
        }

        .editor-actions {
            display: flex;
            gap: 1rem;
            margin-top: 1.5rem;
        }

        .btn-action {
            padding: 0.75rem 2rem;
            border-radius: 50px;
            font-weight: 600;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            transition: all 0.3s ease;
            border: none;
            position: relative;
            overflow: hidden;
        }

        .btn-action::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
            transition: left 0.5s;
        }

        .btn-action:hover::before {
            left: 100%;
        }

        .btn-validate {
            background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
            color: white;
        }

        .btn-parse {
            background: linear-gradient(135deg, #007bff 0%, #6610f2 100%);
            color: white;
        }

        .btn-generate {
            background: linear-gradient(135deg, #fd7e14 0%, #e83e8c 100%);
            color: white;
        }

        .results-section {
            padding: 2rem 0;
            background: #f8f9fa;
        }

        .result-card {
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            margin-bottom: 2rem;
            overflow: hidden;
            transition: transform 0.3s ease;
        }

        .result-card:hover {
            transform: translateY(-5px);
        }

        .result-header {
            padding: 1.5rem;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            font-weight: 600;
            display: flex;
            align-items: center;
            justify-content: between;
        }

        .result-content {
            padding: 2rem;
        }

        .code-block {
            background: #2d3748;
            color: #e2e8f0;
            border-radius: 10px;
            padding: 1.5rem;
            font-family: 'Fira Code', 'Monaco', 'Consolas', monospace;
            font-size: 14px;
            line-height: 1.6;
            overflow-x: auto;
            position: relative;
        }

        .copy-btn {
            position: absolute;
            top: 1rem;
            right: 1rem;
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
            color: white;
            border-radius: 5px;
            padding: 0.5rem;
            cursor: pointer;
            transition: all 0.3s ease;
        }

        .copy-btn:hover {
            background: rgba(255, 255, 255, 0.2);
        }

        .examples-section {
            padding: 3rem 0;
            background: white;
        }

        .example-card {
            background: #f8f9fa;
            border-radius: 15px;
            padding: 2rem;
            margin-bottom: 1.5rem;
            border: 2px solid transparent;
            transition: all 0.3s ease;
            cursor: pointer;
        }

        .example-card:hover {
            border-color: #667eea;
            transform: translateY(-3px);
            box-shadow: 0 10px 30px rgba(102, 126, 234, 0.1);
        }

        .example-title {
            font-weight: 600;
            color: #495057;
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
        }

        .example-title i {
            margin-right: 0.5rem;
            color: #667eea;
        }

        .alert-custom {
            border: none;
            border-radius: 15px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
        }

        .alert-success {
            background: linear-gradient(135deg, #d4edda 0%, #c3e6cb 100%);
            color: #155724;
        }

        .alert-danger {
            background: linear-gradient(135deg, #f8d7da 0%, #f5c6cb 100%);
            color: #721c24;
        }

        .loading-spinner {
            display: none;
            text-align: center;
            padding: 2rem;
        }

        .spinner {
            width: 50px;
            height: 50px;
            border: 4px solid #f3f3f3;
            border-top: 4px solid #667eea;
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .fade-in {
            animation: fadeIn 0.5s ease-in;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .navbar {
            background: rgba(255, 255, 255, 0.95) !important;
            backdrop-filter: blur(10px);
            box-shadow: 0 2px 20px rgba(0, 0, 0, 0.1);
        }

        .navbar-brand {
            font-weight: 700;
            color: #667eea !important;
        }

        .nav-link {
            font-weight: 500;
            color: #495057 !important;
            transition: color 0.3s ease;
        }

        .nav-link:hover {
            color: #667eea !important;
        }

        .result-section {
            display: none;
        }
    </style>
</head>
<body>
    <!-- 导航栏 -->
    <div th:replace="fragments/navigation :: navbar"></div>

    <div class="container mt-5 pt-5">
        <div class="main-container">
            <!-- 页面头部 -->
            <div class="page-header">
                <div class="container">
                    <h1 class="fade-in-up">
                        <i class="bi bi-magic me-3"></i>
                        智能代码生成器
                    </h1>
                    <p class="fade-in-up" style="animation-delay: 0.1s;">
                        输入SQL DDL语句，一键生成完整的CRUD应用代码
                    </p>
                </div>
            </div>

            <!-- SQL输入区域 -->
            <div class="sql-input-section">
                <div class="container">
                    <div class="row">
                        <div class="col-lg-8">
                            <div class="sql-editor fade-in-up">
                                <div class="editor-header">
                                    <div>
                                        <i class="bi bi-code-slash me-2"></i>
                                        SQL DDL 编辑器
                                    </div>
                                    <div>
                                        <small>支持 CREATE TABLE 语句</small>
                                    </div>
                                </div>
                                <div class="p-3">
                                    <textarea 
                                        id="sqlEditor" 
                                        class="form-control" 
                                        placeholder="请输入CREATE TABLE语句...&#10;&#10;示例：&#10;CREATE TABLE users (&#10;    id BIGINT PRIMARY KEY AUTO_INCREMENT,&#10;    username VARCHAR(50) NOT NULL,&#10;    email VARCHAR(100) UNIQUE,&#10;    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP&#10;);"
                                        rows="15"></textarea>
                                </div>
                            </div>

                            <div class="editor-actions fade-in-up" style="animation-delay: 0.1s;">
                                <button id="validateBtn" class="btn btn-action btn-validate">
                                    <i class="bi bi-check-circle me-2"></i>
                                    语法验证
                                </button>
                                <button id="parseBtn" class="btn btn-action btn-parse">
                                    <i class="bi bi-gear me-2"></i>
                                    解析SQL
                                </button>
                                <button id="generateBtn" class="btn btn-action btn-generate">
                                    <i class="bi bi-lightning me-2"></i>
                                    生成代码
                                </button>
                            </div>
                        </div>

                        <div class="col-lg-4">
                            <!-- 快速示例 -->
                            <div class="examples-section">
                                <h4 class="mb-4 fade-in-up">
                                    <i class="bi bi-lightbulb me-2" style="color: #667eea;"></i>
                                    快速示例
                                </h4>
                                
                                <div class="example-card fade-in-up" style="animation-delay: 0.1s;" onclick="loadExample('user')">
                                    <div class="example-title">
                                        <i class="bi bi-person"></i>
                                        用户表示例
                                    </div>
                                    <p class="text-muted mb-0">包含用户基本信息的表结构</p>
                                </div>

                                <div class="example-card fade-in-up" style="animation-delay: 0.2s;" onclick="loadExample('product')">
                                    <div class="example-title">
                                        <i class="bi bi-box"></i>
                                        商品表示例
                                    </div>
                                    <p class="text-muted mb-0">电商商品管理表结构</p>
                                </div>

                                <div class="example-card fade-in-up" style="animation-delay: 0.3s;" onclick="loadExample('order')">
                                    <div class="example-title">
                                        <i class="bi bi-receipt"></i>
                                        订单表示例
                                    </div>
                                    <p class="text-muted mb-0">订单管理系统表结构</p>
                                </div>
                            </div>

                            <!-- 功能说明 -->
                            <div class="mt-4 fade-in-up" style="animation-delay: 0.4s;">
                                <div class="alert alert-info">
                                    <h6><i class="bi bi-info-circle me-2"></i>功能说明</h6>
                                    <ul class="mb-0 small">
                                        <li>支持标准SQL DDL语法</li>
                                        <li>自动生成Spring Boot项目</li>
                                        <li>生成RESTful API接口</li>
                                        <li>包含数据验证逻辑</li>
                                        <li>支持MySQL数据库</li>
                                    </ul>
                                </div>
                            </div>

                            <div class="mt-4 fade-in-up" style="animation-delay: 0.5s;">
                                <div class="card border-0 shadow-sm">
                                    <div class="card-body">
                                        <h6 class="mb-3"><i class="bi bi-sliders me-2"></i>功能开关</h6>
                                        <div class="form-check form-switch mb-2">
                                            <input class="form-check-input" type="checkbox" id="enableSecurity">
                                            <label class="form-check-label" for="enableSecurity">启用鉴权</label>
                                        </div>
                                        <div class="form-check form-switch">
                                            <input class="form-check-input" type="checkbox" id="enableRedis">
                                            <label class="form-check-label" for="enableRedis">启用缓存</label>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 结果展示区域 -->
            <div class="results-section" id="resultsSection" style="display: none;">
                <div class="container">
                    <!-- 加载动画 -->
                    <div class="loading-spinner" id="loadingSpinner">
                        <div class="spinner"></div>
                        <p class="mt-3">正在处理中，请稍候...</p>
                    </div>

                    <!-- 错误信息 -->
                    <div id="errorAlert" class="alert alert-danger alert-custom" style="display: none;">
                        <h6><i class="bi bi-exclamation-triangle me-2"></i>错误信息</h6>
                        <div id="errorMessage"></div>
                    </div>

                    <!-- 成功信息 -->
                    <div id="successAlert" class="alert alert-success alert-custom" style="display: none;">
                        <h6><i class="bi bi-check-circle me-2"></i>操作成功</h6>
                        <div id="successMessage"></div>
                    </div>

                    <!-- 解析结果 -->
                    <div class="result-card" id="parseResult" style="display: none;">
                        <div class="result-header">
                            <div>
                                <i class="bi bi-search me-2"></i>
                                SQL解析结果
                            </div>
                            <button class="btn btn-sm btn-outline-light" onclick="copyToClipboard('parseResultContent')">
                                <i class="bi bi-clipboard"></i>
                            </button>
                        </div>
                        <div class="result-content">
                            <div id="tableInfo"></div>
                        </div>
                    </div>

                    <!-- 生成结果 -->
                    <div class="result-card" id="generateResult" style="display: none;">
                        <div class="result-header">
                            <div>
                                <i class="bi bi-file-code me-2"></i>
                                代码生成结果
                            </div>
                            <div>
                                <button class="btn btn-sm btn-outline-light me-2" onclick="downloadCode()">
                                    <i class="bi bi-download me-1"></i>
                                    下载代码
                                </button>
                                <button class="btn btn-sm btn-outline-light" onclick="copyToClipboard('generateResultContent')">
                                    <i class="bi bi-clipboard"></i>
                                </button>
                            </div>
                        </div>
                        <div class="result-content">
                            <div id="generateInfo"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- JavaScript -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-core.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.29.0/components/prism-sql.min.js"></script>
    <script src="/js/common.js"></script>
    
    <script>
        // SQL示例数据
        const sqlExamples = {
            user: `CREATE TABLE users (
    id BIGINT PRIMARY KEY AUTO_INCREMENT COMMENT '用户ID',
    username VARCHAR(50) NOT NULL COMMENT '用户名',
    email VARCHAR(100) UNIQUE COMMENT '邮箱',
    password VARCHAR(255) NOT NULL COMMENT '密码',
    phone VARCHAR(20) COMMENT '手机号',
    avatar VARCHAR(255) COMMENT '头像URL',
    status TINYINT DEFAULT 1 COMMENT '状态：1-正常，0-禁用',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间'
) COMMENT='用户表';`,
            
            product: `CREATE TABLE products (
    id BIGINT PRIMARY KEY AUTO_INCREMENT COMMENT '商品ID',
    name VARCHAR(100) NOT NULL COMMENT '商品名称',
    description TEXT COMMENT '商品描述',
    price DECIMAL(10,2) NOT NULL COMMENT '价格',
    stock_quantity INT DEFAULT 0 COMMENT '库存数量',
    category_id BIGINT COMMENT '分类ID',
    brand VARCHAR(50) COMMENT '品牌',
    sku VARCHAR(100) UNIQUE COMMENT 'SKU编码',
    status TINYINT DEFAULT 1 COMMENT '状态：1-上架，0-下架',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间'
) COMMENT='商品表';`,
            
            order: `CREATE TABLE orders (
    id BIGINT PRIMARY KEY AUTO_INCREMENT COMMENT '订单ID',
    order_no VARCHAR(32) UNIQUE NOT NULL COMMENT '订单号',
    user_id BIGINT NOT NULL COMMENT '用户ID',
    total_amount DECIMAL(10,2) NOT NULL COMMENT '订单总金额',
    status TINYINT DEFAULT 1 COMMENT '订单状态：1-待付款，2-已付款，3-已发货，4-已完成，5-已取消',
    payment_method TINYINT COMMENT '支付方式：1-支付宝，2-微信，3-银行卡',
    shipping_address TEXT COMMENT '收货地址',
    remark TEXT COMMENT '订单备注',
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间'
) COMMENT='订单表';`
        };

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            initializeEventListeners();
            initializeAnimations();
        });

        // 初始化事件监听器
        function initializeEventListeners() {
            // 语法验证按钮
            document.getElementById('validateBtn').addEventListener('click', function() {
                validateSql();
            });

            // SQL解析按钮
            document.getElementById('parseBtn').addEventListener('click', function() {
                parseSql();
            });

            // 代码生成按钮
            document.getElementById('generateBtn').addEventListener('click', function() {
                generateCode();
            });

            // SQL输入框变化监听
            document.getElementById('sqlEditor').addEventListener('input', function() {
                hideResults();
            });
        }

        // 初始化动画
        function initializeAnimations() {
            // 添加滚动监听，实现元素进入视口时的动画
            const observerOptions = {
                threshold: 0.1,
                rootMargin: '0px 0px -50px 0px'
            };

            const observer = new IntersectionObserver(function(entries) {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        entry.target.classList.add('animate');
                    }
                });
            }, observerOptions);

            // 观察所有需要动画的元素
            document.querySelectorAll('.fade-in-up').forEach(el => {
                observer.observe(el);
            });
        }

        // 加载示例SQL
        function loadExample(type) {
            if (sqlExamples[type]) {
                document.getElementById('sqlEditor').value = sqlExamples[type];
                hideResults();
                
                // 添加视觉反馈
                const textarea = document.getElementById('sqlEditor');
                textarea.focus();
                textarea.scrollTop = 0;
                
                // 显示成功提示
                showToast('示例已加载', 'success');
            }
        }

        // 隐藏结果区域
        function hideResults() {
            document.getElementById('resultsSection').style.display = 'none';
            document.getElementById('parseResult').style.display = 'none';
            document.getElementById('generateResult').style.display = 'none';
            document.getElementById('errorAlert').style.display = 'none';
            document.getElementById('successAlert').style.display = 'none';
        }

        // 显示错误信息
        function showError(message) {
            document.getElementById('resultsSection').style.display = 'block';
            document.getElementById('errorAlert').style.display = 'block';
            document.getElementById('errorMessage').innerHTML = message;
            document.getElementById('successAlert').style.display = 'none';
            
            // 滚动到结果区域
            document.getElementById('resultsSection').scrollIntoView({ 
                behavior: 'smooth', 
                block: 'start' 
            });
        }

        // 显示成功信息
        function showSuccess(message) {
            document.getElementById('resultsSection').style.display = 'block';
            document.getElementById('successAlert').style.display = 'block';
            document.getElementById('successMessage').innerHTML = message;
            document.getElementById('errorAlert').style.display = 'none';
            
            // 滚动到结果区域
            document.getElementById('resultsSection').scrollIntoView({ 
                behavior: 'smooth', 
                block: 'start' 
            });
        }

        // 显示加载动画
        function showLoading() {
            document.getElementById('resultsSection').style.display = 'block';
            document.getElementById('loadingSpinner').style.display = 'block';
            hideResults();
        }

        // 隐藏加载动画
        function hideLoading() {
            document.getElementById('loadingSpinner').style.display = 'none';
        }

        // 语法验证
        function validateSql() {
            const ddl = document.getElementById('sqlEditor').value.trim();
            
            if (!ddl) {
                showError('请输入SQL语句');
                return;
            }

            // 简单的客户端验证
            if (!ddl.toUpperCase().includes('CREATE TABLE')) {
                showError('请输入有效的CREATE TABLE语句');
                return;
            }

            showSuccess('SQL语法验证通过！');
        }

        // SQL解析
        function parseSql() {
            const ddl = document.getElementById('sqlEditor').value.trim();
            
            if (!ddl) {
                showError('请输入SQL语句');
                return;
            }

            showLoading();

            // 检查是否包含多个CREATE TABLE语句
            const createTableCount = (ddl.match(/CREATE\s+TABLE/gi) || []).length;
            
            if (createTableCount > 1) {
                // 使用多表解析接口
                fetch('/api/generator/parse-multiple-sql', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ ddl: ddl })
                })
                .then(response => response.json())
                .then(data => {
                    hideLoading();
                    if (data.code === 200) {
                        showMultipleParseResult(data.data);
                    } else {
                        showError('解析失败：' + data.message);
                    }
                })
                .catch(error => {
                    hideLoading();
                    showError('解析失败：' + error.message);
                });
            } else {
                // 使用单表解析接口
                fetch('/api/generator/parse-sql', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ ddl: ddl })
                })
                .then(response => response.json())
                .then(data => {
                    hideLoading();
                    if (data.code === 200) {
                        showParseResult(data.data);
                    } else {
                        showError('解析失败：' + data.message);
                    }
                })
                .catch(error => {
                    hideLoading();
                    showError('解析失败：' + error.message);
                });
            }
        }

        // 显示解析结果
        function showParseResult(data) {
            document.getElementById('resultsSection').style.display = 'block';
            document.getElementById('parseResult').style.display = 'block';
            
            let html = `
                <div class="row">
                    <div class="col-md-6">
                        <h6><i class="bi bi-table me-2"></i>表信息</h6>
                        <div class="table-responsive">
                            <table class="table table-sm">
                                <tr><td><strong>表名</strong></td><td>${data.tableName}</td></tr>
                                <tr><td><strong>注释</strong></td><td>${data.tableComment || '无'}</td></tr>
                                <tr><td><strong>字段数量</strong></td><td>${data.columns.length}</td></tr>
                            </table>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <h6><i class="bi bi-gear me-2"></i>生成配置</h6>
                        <div class="table-responsive">
                            <table class="table table-sm">
                                <tr><td><strong>实体类名</strong></td><td>${data.tableName.charAt(0).toUpperCase() + data.tableName.slice(1)}</td></tr>
                                <tr><td><strong>包名</strong></td><td>com.example.${data.tableName}</td></tr>
                                <tr><td><strong>API路径</strong></td><td>/api/${data.tableName}</td></tr>
                            </table>
                        </div>
                    </div>
                </div>
                
                <h6 class="mt-4"><i class="bi bi-list-ul me-2"></i>字段详情</h6>
                <div class="table-responsive">
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th>字段名</th>
                                <th>数据类型</th>
                                <th>Java类型</th>
                                <th>约束</th>
                                <th>注释</th>
                            </tr>
                        </thead>
                        <tbody>
            `;
            
            data.columns.forEach(column => {
                html += `
                    <tr>
                        <td><code>${column.columnName}</code></td>
                        <td><span class="badge bg-secondary">${column.dataType}</span></td>
                        <td><span class="badge bg-primary">${column.javaType}</span></td>
                        <td>
                            ${column.primaryKey ? '<span class="badge bg-warning">主键</span> ' : ''}
                            ${!column.nullable ? '<span class="badge bg-danger">非空</span> ' : ''}
                            ${column.autoIncrement ? '<span class="badge bg-success">自增</span> ' : ''}
                        </td>
                        <td>${column.columnComment || '无'}</td>
                    </tr>
                `;
            });
            
            html += `
                        </tbody>
                    </table>
                </div>
            `;
            
            document.getElementById('tableInfo').innerHTML = html;
            
            // 滚动到结果区域
            document.getElementById('resultsSection').scrollIntoView({ 
                behavior: 'smooth', 
                block: 'start' 
            });
        }
        
        // 显示多表解析结果
        function showMultipleParseResult(tables) {
            document.getElementById('resultsSection').style.display = 'block';
            document.getElementById('parseResult').style.display = 'block';
            
            // 存储解析的表数据
            window.parsedTables = tables;
            
            let html = `
                <div class="alert alert-success">
                    <h6><i class="bi bi-check-circle me-2"></i>多表解析成功！</h6>
                    <p class="mb-0">共解析了 ${tables.length} 个表，请选择要生成代码的表：</p>
                </div>
                
                <div class="row">
                    <div class="col-md-12">
                        <h6><i class="bi bi-table me-2"></i>表列表</h6>
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th width="50">选择</th>
                                        <th>表名</th>
                                        <th>注释</th>
                                        <th>字段数</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody>
            `;
            
            tables.forEach((table, index) => {
                html += `
                    <tr>
                        <td>
                            <input type="radio" name="selectedTable" value="${index}" id="table_${index}" class="form-check-input">
                        </td>
                        <td>
                            <label for="table_${index}" class="form-check-label">
                                <code>${table.tableName}</code>
                            </label>
                        </td>
                        <td>${table.tableComment || '无'}</td>
                        <td><span class="badge bg-primary">${table.columns.length}</span></td>
                        <td>
                            <button class="btn btn-sm btn-outline-info" onclick="showTableDetails(${index})">
                                <i class="bi bi-eye me-1"></i>查看详情
                            </button>
                        </td>
                    </tr>
                `;
            });
            
            html += `
                                </tbody>
                            </table>
                        </div>
                        
                        <div class="mt-3">
                            <button class="btn btn-primary" onclick="generateSelectedTable()">
                                <i class="bi bi-code-slash me-2"></i>生成选中表的代码
                            </button>
                            <button class="btn btn-outline-secondary ms-2" onclick="generateAllTables()">
                                <i class="bi bi-collection me-2"></i>生成所有表的代码
                            </button>
                        </div>
                    </div>
                </div>
                
                <div id="tableDetailsArea" class="mt-4" style="display: none;">
                    <h6><i class="bi bi-info-circle me-2"></i>表详情</h6>
                    <div id="tableDetailsContent"></div>
                </div>
            `;
            
            document.getElementById('tableInfo').innerHTML = html;
            
            // 滚动到结果区域
            document.getElementById('resultsSection').scrollIntoView({ 
                behavior: 'smooth', 
                block: 'start' 
            });
        }

        // 显示表详情
        function showTableDetails(tableIndex) {
            if (!window.parsedTables || !window.parsedTables[tableIndex]) {
                showToast('表数据不存在', 'error');
                return;
            }
            
            const table = window.parsedTables[tableIndex];
            document.getElementById('tableDetailsArea').style.display = 'block';
            
            let html = `
                <div class="card">
                    <div class="card-header">
                        <h6 class="mb-0"><i class="bi bi-table me-2"></i>${table.tableName} - 详细信息</h6>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <h6><i class="bi bi-info-circle me-2"></i>基本信息</h6>
                                <div class="table-responsive">
                                    <table class="table table-sm">
                                        <tr><td><strong>表名</strong></td><td>${table.tableName}</td></tr>
                                        <tr><td><strong>注释</strong></td><td>${table.tableComment || '无'}</td></tr>
                                        <tr><td><strong>字段数量</strong></td><td>${table.columns.length}</td></tr>
                                    </table>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <h6><i class="bi bi-gear me-2"></i>生成配置</h6>
                                <div class="table-responsive">
                                    <table class="table table-sm">
                                        <tr><td><strong>实体类名</strong></td><td>${table.tableName.charAt(0).toUpperCase() + table.tableName.slice(1)}</td></tr>
                                        <tr><td><strong>包名</strong></td><td>com.example.${table.tableName}</td></tr>
                                        <tr><td><strong>API路径</strong></td><td>/api/${table.tableName}</td></tr>
                                    </table>
                                </div>
                            </div>
                        </div>
                        
                        <h6 class="mt-4"><i class="bi bi-list-ul me-2"></i>字段详情</h6>
                        <div class="table-responsive">
                            <table class="table table-striped">
                                <thead>
                                    <tr>
                                        <th>字段名</th>
                                        <th>数据类型</th>
                                        <th>Java类型</th>
                                        <th>约束</th>
                                        <th>注释</th>
                                    </tr>
                                </thead>
                                <tbody>
            `;
            
            table.columns.forEach(column => {
                html += `
                    <tr>
                        <td><code>${column.columnName}</code></td>
                        <td><span class="badge bg-secondary">${column.dataType}</span></td>
                        <td><span class="badge bg-primary">${column.javaType}</span></td>
                        <td>
                            ${column.primaryKey ? '<span class="badge bg-warning">主键</span> ' : ''}
                            ${!column.nullable ? '<span class="badge bg-danger">非空</span> ' : ''}
                            ${column.autoIncrement ? '<span class="badge bg-success">自增</span> ' : ''}
                        </td>
                        <td>${column.columnComment || '无'}</td>
                    </tr>
                `;
            });
            
            html += `
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            `;
            
            document.getElementById('tableDetailsContent').innerHTML = html;
            
            // 滚动到详情区域
            document.getElementById('tableDetailsArea').scrollIntoView({ 
                behavior: 'smooth', 
                block: 'start' 
            });
        }
        
        // 生成选中表的代码
        function generateSelectedTable() {
            const selectedRadio = document.querySelector('input[name="selectedTable"]:checked');
            if (!selectedRadio) {
                showToast('请先选择一个表', 'warning');
                return;
            }
            
            const tableIndex = parseInt(selectedRadio.value);
            const selectedTable = window.parsedTables[tableIndex];
            
            // 构造单表的DDL
            const ddl = document.getElementById('sqlEditor').value.trim();
            const tableName = selectedTable.tableName;
            
            // 从原始DDL中提取选中表的CREATE TABLE语句
            const regex = new RegExp(`CREATE\\s+TABLE\\s+${tableName}[\\s\\S]*?;`, 'gi');
            const match = ddl.match(regex);
            
            if (!match) {
                showToast('无法找到选中表的DDL语句', 'error');
                return;
            }
            
            const singleTableDdl = match[0];
            generateCodeWithDdl(singleTableDdl);
        }
        
        // 生成所有表的代码
        function generateAllTables() {
            const ddl = document.getElementById('sqlEditor').value.trim();
            generateCodeWithDdl(ddl);
        }
        
        // 使用指定DDL生成代码
        function generateCodeWithDdl(ddl) {
            if (!ddl) {
                showError('DDL语句不能为空');
                return;
            }

            showLoading();

            // 检查是否包含多个CREATE TABLE语句
            const createTableCount = (ddl.match(/CREATE\s+TABLE/gi) || []).length;
            
            if (createTableCount > 1) {
                // 使用多表代码生成接口
                fetch('/api/generator/generate-multiple-code', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ ddl: ddl })
                })
                .then(response => response.json())
                .then(data => {
                    hideLoading();
                    if (data.code === 200) {
                        showMultipleGenerateResult(data.data);
                    } else {
                        showError('多表代码生成失败：' + data.message);
                    }
                })
                .catch(error => {
                    hideLoading();
                    showError('多表代码生成失败：' + error.message);
                });
            } else {
                // 使用单表代码生成接口
                fetch('/api/generator/generate-code', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ ddl: ddl })
                })
                .then(response => response.json())
                .then(data => {
                    hideLoading();
                    if (data.code === 200) {
                        showGenerateResult(data.data);
                    } else {
                        showError('代码生成失败：' + data.message);
                    }
                })
                .catch(error => {
                    hideLoading();
                    showError('代码生成失败：' + error.message);
                });
            }
        }
        
        // 代码生成
        function generateCode() {
            const ddl = document.getElementById('sqlEditor').value.trim();
            
            if (!ddl) {
                showError('请输入SQL语句');
                return;
            }

            showLoading();

            fetch('/api/generator/generate-code', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ ddl: ddl })
            })
            .then(response => response.json())
            .then(data => {
                hideLoading();
                if (data.code === 200) {
                    showGenerateResult(data.data);
                } else {
                    showError('生成失败：' + data.message);
                }
            })
            .catch(error => {
                hideLoading();
                showError('生成失败：' + error.message);
            });
        }

        // 显示生成结果
        function showGenerateResult(data) {
            document.getElementById('resultsSection').style.display = 'block';
            document.getElementById('generateResult').style.display = 'block';
            
            // 适配后端返回的数据格式
            const files = data.files || {};
            const fileCount = Object.keys(files).length;
            
            let html = `
                <div class="alert alert-success">
                    <h6><i class="bi bi-check-circle me-2"></i>代码生成成功！</h6>
                    <p class="mb-0">已生成 ${fileCount} 个文件，包含完整的Spring Boot项目结构。</p>
                </div>
            `;
            
            if (fileCount > 0) {
                html += `
                    <div class="row">
                        <div class="col-md-6">
                            <h6><i class="bi bi-folder me-2"></i>生成的文件</h6>
                            <div class="list-group">
                `;
                
                Object.keys(files).forEach(fileName => {
                    const fileType = getFileType(fileName);
                    html += `
                        <div class="list-group-item d-flex justify-content-between align-items-center">
                            <div>
                                <i class="bi ${fileType.icon} me-2" style="color: ${fileType.color};"></i>
                                <code>${fileName}</code>
                            </div>
                            <button class="btn btn-sm btn-outline-primary" onclick="showFileContent('${fileName}')">
                                查看
                            </button>
                        </div>
                    `;
                });
                
                html += `
                            </div>
                        </div>
                        <div class="col-md-6">
                            <h6><i class="bi bi-info-circle me-2"></i>项目信息</h6>
                            <div class="table-responsive">
                                <table class="table table-sm">
                                    <tr><td><strong>表名</strong></td><td>${data.tableName || '未知'}</td></tr>
                                    <tr><td><strong>实体类</strong></td><td>${data.entityName || '未知'}</td></tr>
                                    <tr><td><strong>生成时间</strong></td><td>${new Date().toLocaleString()}</td></tr>
                                    <tr><td><strong>文件数量</strong></td><td>${fileCount}</td></tr>
                                </table>
                            </div>
                            
                            <div class="mt-3">
                                <button class="btn btn-outline-secondary btn-sm" onclick="copyProjectInfo()">
                                    <i class="bi bi-clipboard me-1"></i>
                                    复制项目信息
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <div id="fileContentArea" class="mt-4" style="display: none;">
                        <h6><i class="bi bi-file-code me-2"></i>文件内容</h6>
                        <div class="code-block">
                            <button class="copy-btn" onclick="copyFileContent()">
                                <i class="bi bi-clipboard"></i>
                            </button>
                            <pre><code id="fileContent"></code></pre>
                        </div>
                    </div>
                `;
                
                // 存储生成的文件数据
                window.generatedFiles = files;
            } else {
                html += `
                    <div class="alert alert-warning">
                        <h6><i class="bi bi-exclamation-triangle me-2"></i>注意</h6>
                        <p class="mb-0">代码生成完成，但没有返回文件内容。请检查后端实现。</p>
                    </div>
                `;
            }
            
            document.getElementById('generateInfo').innerHTML = html;
            
            // 滚动到结果区域
            document.getElementById('resultsSection').scrollIntoView({ 
                behavior: 'smooth', 
                block: 'start' 
            });
        }

        // 显示多表生成结果
        function showMultipleGenerateResult(data) {
            document.getElementById('resultsSection').style.display = 'block';
            document.getElementById('generateResult').style.display = 'block';
            
            // 适配后端返回的数据格式
            const files = data.files || {};
            const tables = data.tables || [];
            const fileCount = data.totalFiles || Object.keys(files).length;
            const tableCount = data.successTables || tables.length;
            
            let html = `
                <div class="alert alert-success">
                    <h6><i class="bi bi-check-circle me-2"></i>多表代码生成成功！</h6>
                    <p class="mb-0">已生成 ${tableCount} 个表的代码，共 ${fileCount} 个文件，包含完整的Spring Boot项目结构。</p>
                </div>
            `;
            
            if (fileCount > 0) {
                html += `
                    <div class="row">
                        <div class="col-md-6">
                            <h6><i class="bi bi-folder me-2"></i>生成的文件</h6>
                            <div class="list-group" style="max-height: 400px; overflow-y: auto;">
                `;
                
                Object.keys(files).forEach(fileName => {
                    const fileType = getFileType(fileName);
                    html += `
                        <div class="list-group-item d-flex justify-content-between align-items-center">
                            <div>
                                <i class="bi ${fileType.icon} me-2" style="color: ${fileType.color};"></i>
                                <code>${fileName}</code>
                            </div>
                            <button class="btn btn-sm btn-outline-primary" onclick="showFileContent('${fileName}')">
                                查看
                            </button>
                        </div>
                    `;
                });
                
                html += `
                            </div>
                        </div>
                        <div class="col-md-6">
                            <h6><i class="bi bi-info-circle me-2"></i>项目信息</h6>
                            <div class="table-responsive">
                                <table class="table table-sm">
                                    <tr><td><strong>总表数</strong></td><td>${data.totalTables || 0}</td></tr>
                                    <tr><td><strong>成功生成</strong></td><td>${tableCount}</td></tr>
                                    <tr><td><strong>生成时间</strong></td><td>${new Date().toLocaleString()}</td></tr>
                                    <tr><td><strong>文件数量</strong></td><td>${fileCount}</td></tr>
                                </table>
                            </div>
                            
                            <h6 class="mt-3"><i class="bi bi-table me-2"></i>生成的表</h6>
                            <div class="list-group" style="max-height: 200px; overflow-y: auto;">
                `;
                
                tables.forEach(table => {
                    html += `
                        <div class="list-group-item d-flex justify-content-between align-items-center">
                            <div>
                                <strong>${table.tableName}</strong>
                                <br><small class="text-muted">${table.columnCount} 个字段</small>
                            </div>
                            <span class="badge bg-success">✓</span>
                        </div>
                    `;
                });
                
                html += `
                            </div>
                            
                            <div class="mt-3">
                                <button class="btn btn-outline-secondary btn-sm" onclick="copyMultipleProjectInfo()">
                                    <i class="bi bi-clipboard me-1"></i>
                                    复制项目信息
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <div id="fileContentArea" class="mt-4" style="display: none;">
                        <h6><i class="bi bi-file-code me-2"></i>文件内容</h6>
                        <div class="code-block">
                            <button class="copy-btn" onclick="copyFileContent()">
                                <i class="bi bi-clipboard"></i>
                            </button>
                            <pre><code id="fileContent"></code></pre>
                        </div>
                    </div>
                `;
                
                // 存储生成的文件数据
                window.generatedFiles = files;
                window.generatedTables = tables;
            } else {
                html += `
                    <div class="alert alert-warning">
                        <h6><i class="bi bi-exclamation-triangle me-2"></i>注意</h6>
                        <p class="mb-0">多表代码生成完成，但没有返回文件内容。请检查后端实现。</p>
                    </div>
                `;
            }
            
            document.getElementById('generateInfo').innerHTML = html;
            
            // 滚动到结果区域
            document.getElementById('resultsSection').scrollIntoView({ 
                behavior: 'smooth', 
                block: 'start' 
            });
        }

        // 获取文件类型信息
        function getFileType(fileName) {
            if (fileName.endsWith('.java')) {
                return { icon: 'bi-file-earmark-code', color: '#f89820' };
            } else if (fileName.endsWith('.xml')) {
                return { icon: 'bi-file-earmark-text', color: '#e34c26' };
            } else if (fileName.endsWith('.properties')) {
                return { icon: 'bi-file-earmark-text', color: '#6f42c1' };
            } else if (fileName.endsWith('.sql')) {
                return { icon: 'bi-database', color: '#336791' };
            } else if (fileName.endsWith('.md')) {
                return { icon: 'bi-file-earmark-text', color: '#083fa1' };
            }
            return { icon: 'bi-file-earmark', color: '#6c757d' };
        }

        // 显示文件内容
        function showFileContent(fileName) {
            if (window.generatedFiles && window.generatedFiles[fileName]) {
                document.getElementById('fileContentArea').style.display = 'block';
                document.getElementById('fileContent').textContent = window.generatedFiles[fileName];
                
                // 代码高亮
                Prism.highlightElement(document.getElementById('fileContent'));
                
                // 滚动到文件内容区域
                document.getElementById('fileContentArea').scrollIntoView({ 
                    behavior: 'smooth', 
                    block: 'start' 
                });
            }
        }

        // 复制到剪贴板
        function copyToClipboard(elementId) {
            const element = document.getElementById(elementId);
            const text = element.textContent || element.innerText;
            
            navigator.clipboard.writeText(text).then(() => {
                showToast('已复制到剪贴板', 'success');
            }).catch(() => {
                showToast('复制失败', 'error');
            });
        }

        // 复制文件内容
        function copyFileContent() {
            const content = document.getElementById('fileContent').textContent;
            navigator.clipboard.writeText(content).then(() => {
                showToast('文件内容已复制到剪贴板', 'success');
            }).catch(() => {
                showToast('复制失败', 'error');
            });
        }

        // 复制项目信息
        function copyProjectInfo() {
            const info = `项目名称: ${window.generatedFiles ? Object.keys(window.generatedFiles).length + ' 个文件' : '未知'}
Spring Boot版本: 3.2.0
Java版本: 17
生成时间: ${new Date().toLocaleString()}`;
            
            navigator.clipboard.writeText(info).then(() => {
                showToast('项目信息已复制到剪贴板', 'success');
            }).catch(() => {
                showToast('复制失败', 'error');
            });
        }

        // 复制多表项目信息
        function copyMultipleProjectInfo() {
            const tables = window.generatedTables || [];
            const files = window.generatedFiles || {};
            
            let info = `多表CRUD项目信息:
`;
            info += `Spring Boot版本: 3.2.0
`;
            info += `Java版本: 17
`;
            info += `生成时间: ${new Date().toLocaleString()}
`;
            info += `总文件数: ${Object.keys(files).length}
`;
            info += `生成表数: ${tables.length}

`;
            info += `生成的表:
`;
            
            tables.forEach((table, index) => {
                info += `${index + 1}. ${table.tableName} (${table.columnCount} 个字段)
`;
            });
            
            navigator.clipboard.writeText(info).then(() => {
                showToast('多表项目信息已复制到剪贴板', 'success');
            }).catch(() => {
                showToast('复制失败', 'error');
            });
        }

        // 下载代码
        function downloadCode() {
            const ddl = document.getElementById('sqlEditor').value.trim();
            
            if (!ddl) {
                showToast('请先输入CREATE TABLE语句', 'warning');
                return;
            }
            
            showToast('正在打包下载文件...', 'info');
            
            const enableSecurity = !!document.getElementById('enableSecurity')?.checked;
            const enableRedis = !!document.getElementById('enableRedis')?.checked;
            const requestData = {
                ddl: ddl,
                packagePrefix: document.getElementById('packagePrefix')?.value || 'com.example',
                author: document.getElementById('author')?.value || 'CRUD-Generator',
                enableSecurity: enableSecurity,
                enableRedis: enableRedis
            };
            
            // 检测CREATE TABLE语句数量
            const createTableMatches = ddl.match(/CREATE\s+TABLE/gi);
            const tableCount = createTableMatches ? createTableMatches.length : 0;
            
            // 根据表数量选择下载接口
            const downloadUrl = tableCount > 1 ? '/api/generator/download-multiple-code' : '/api/generator/download-code';
            
            console.log(`检测到 ${tableCount} 个表，使用接口: ${downloadUrl}`);
            
            // 使用fetch API下载文件
            fetch(downloadUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(requestData)
            })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(err => {
                        throw new Error(err.message || '下载失败');
                    });
                }
                
                // 获取文件名
                const contentDisposition = response.headers.get('Content-Disposition');
                let fileName = 'crud-code.zip';
                if (contentDisposition) {
                    const fileNameMatch = contentDisposition.match(/filename="(.+)"/); 
                    if (fileNameMatch) {
                        fileName = fileNameMatch[1];
                    }
                }
                
                return response.blob().then(blob => ({ blob, fileName }));
            })
            .then(({ blob, fileName }) => {
                // 创建下载链接
                const url = window.URL.createObjectURL(blob);
                const a = document.createElement('a');
                a.href = url;
                a.download = fileName;
                document.body.appendChild(a);
                a.click();
                
                // 清理
                window.URL.revokeObjectURL(url);
                document.body.removeChild(a);
                
                showToast('代码包下载成功！', 'success');
            })
            .catch(error => {
                console.error('下载失败:', error);
                showToast('下载失败: ' + error.message, 'error');
            });
        }

        // 显示Toast消息
        function showToast(message, type = 'info') {
            // 创建toast元素
            const toast = document.createElement('div');
            toast.className = `alert alert-${type === 'error' ? 'danger' : type === 'success' ? 'success' : 'info'} position-fixed`;
            toast.style.cssText = `
                top: 20px;
                right: 20px;
                z-index: 9999;
                min-width: 300px;
                animation: slideInRight 0.3s ease-out;
            `;
            toast.innerHTML = `
                <i class="bi bi-${type === 'error' ? 'exclamation-triangle' : type === 'success' ? 'check-circle' : 'info-circle'} me-2"></i>
                ${message}
                <button type="button" class="btn-close" onclick="this.parentElement.remove()"></button>
            `;
            
            document.body.appendChild(toast);
            
            // 3秒后自动移除
            setTimeout(() => {
                if (toast.parentElement) {
                    toast.remove();
                }
            }, 3000);
        }
    </script>

    <style>
        @keyframes slideInRight {
            from {
                transform: translateX(100%);
                opacity: 0;
            }
            to {
                transform: translateX(0);
                opacity: 1;
            }
        }
    </style>
</body>
</html>
